package org.jeecg.modules.zhibiao.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.zhibiao.entity.CaiwuZhibiao;
import org.jeecg.modules.zhibiao.service.ICaiwuZhibiaoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: caiwu_zhibiao
 * @Author: jeecg-boot
 * @Date:   2020-06-10
 * @Version: V1.0
 */
@Api(tags="caiwu_zhibiao")
@RestController
@RequestMapping("/zhibiao/caiwuZhibiao")
@Slf4j
public class CaiwuZhibiaoController extends JeecgController<CaiwuZhibiao, ICaiwuZhibiaoService> {
	@Autowired
	private ICaiwuZhibiaoService caiwuZhibiaoService;

	 @Autowired
	 private ISysCategoryService sysCategoryService;

	/**
	 * 分页列表查询
	 *
	 * @param caiwuZhibiao
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-分页列表查询")
	@ApiOperation(value="caiwu_zhibiao-分页列表查询", notes="caiwu_zhibiao-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CaiwuZhibiao caiwuZhibiao,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CaiwuZhibiao> queryWrapper = QueryGenerator.initQueryWrapper(caiwuZhibiao, req.getParameterMap());
		Page<CaiwuZhibiao> page = new Page<CaiwuZhibiao>(pageNo, pageSize);
		IPage<CaiwuZhibiao> pageList = caiwuZhibiaoService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param caiwuZhibiaoList
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-添加")
	@ApiOperation(value="caiwu_zhibiao-添加", notes="caiwu_zhibiao-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody List<CaiwuZhibiao> caiwuZhibiaoList) {
		caiwuZhibiaoService.saveOrUpdateBatch(caiwuZhibiaoList);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param caiwuZhibiao
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-编辑")
	@ApiOperation(value="caiwu_zhibiao-编辑", notes="caiwu_zhibiao-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CaiwuZhibiao caiwuZhibiao) {
		caiwuZhibiaoService.updateById(caiwuZhibiao);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-通过id删除")
	@ApiOperation(value="caiwu_zhibiao-通过id删除", notes="caiwu_zhibiao-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		caiwuZhibiaoService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-批量删除")
	@ApiOperation(value="caiwu_zhibiao-批量删除", notes="caiwu_zhibiao-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.caiwuZhibiaoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "caiwu_zhibiao-通过id查询")
	@ApiOperation(value="caiwu_zhibiao-通过id查询", notes="caiwu_zhibiao-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CaiwuZhibiao caiwuZhibiao = caiwuZhibiaoService.getById(id);
		if(caiwuZhibiao==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(caiwuZhibiao);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param caiwuZhibiao
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CaiwuZhibiao caiwuZhibiao) {
        return super.exportXls(request, caiwuZhibiao, CaiwuZhibiao.class, "caiwu_zhibiao");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CaiwuZhibiao.class);
    }

	 /**
	  * 列表查询
	  * @return
	  */
	 @GetMapping(value = "/rootList")
	 public Result<List<SysCategory>> queryPageList(String deptId,String categoryPid) {
//		 if(oConvertUtils.isEmpty(sysCategory.getPid())){
//			 sysCategory.setPid("0");
//		 }
		 Result<List<SysCategory>> result = new Result<>();

//		 List<SysCategory> list = this.caiwuZhibiaoService.listZhibiao(deptId,categoryPid);
//		 result.setSuccess(true);
//		 result.setResult(list);
		 return result;
	 }

	 @GetMapping(value = "/childList")
	 public Result<List<SysCategory>> queryPageList(SysCategory sysCategory,HttpServletRequest req) {
		 Result<List<SysCategory>> result = new Result<List<SysCategory>>();
		 QueryWrapper<SysCategory> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
		 List<SysCategory> list = sysCategoryService.list(queryWrapper);
		 result.setSuccess(true);
		 result.setResult(list);
		 return result;
	 }

	 /**
	  * 加载一级节点/如果是同步 则所有数据
	  */
	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam("deptId")String deptId, @RequestParam(name="async") Boolean async,@RequestParam(name="pid") String pid) {
		 Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
		 try {
			 List<TreeSelectModel> ls = this.caiwuZhibiaoService.listZhibiao(deptId,pid);
//			 List<TreeSelectModel> ls = this.sysCategoryService.queryListByCode(pcode);
			 if(!async) {
				 loadAllCategoryChildren(deptId,ls);
			 }
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 递归求子节点 同步加载用到
	  */
	 private void loadAllCategoryChildren(String deptId,List<TreeSelectModel> ls) {
		 for (TreeSelectModel tsm : ls) {
			 List<TreeSelectModel> temp = this.caiwuZhibiaoService.listZhibiao(deptId,tsm.getKey());
			 if(temp!=null && temp.size()>0) {
				 tsm.setChildren(temp);
				 loadAllCategoryChildren(deptId,temp);
			 }
		 }
	 }

	 @RequestMapping(value = "/loadAllData", method = RequestMethod.GET)
	 public Result<List<DictModel>> loadAllData(@RequestParam("deptId") String deptId,@RequestParam(name="code") String code) {
		 Result<List<DictModel>> result = new Result<List<DictModel>>();
		 LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>();

		 List<TreeSelectModel> list = this.caiwuZhibiaoService.loadAllData(deptId,code);
		 if(list==null || list.size()==0) {
			 result.setMessage("无数据,参数有误.[code]");
			 result.setSuccess(false);
			 return result;
		 }
		 List<DictModel> rdList = new ArrayList<DictModel>();
		 for (TreeSelectModel c : list) {
		 	String title = c.getTitle();
		 	if(c.isLeaf()) {
				title += "(" + (c.getValue() == null ? "0" : c.getValue())+ ")";
			}
			 rdList.add(new DictModel(c.getKey(),title));
		 }
		 result.setSuccess(true);
		 result.setResult(rdList);
		 return result;
	 }
}
